from sanic.request import Request

from utils.common import UniqCode
from utils.response import general_json_res

"""
Author: Gaoqiang Du
Description：Sanic middleware, can be used in app or blueprints
Date: 2022/2/11 14:26
"""


async def check_market_from(request: Request):
    """检测市场来源（主要用于移动端项目）"""
    market_from = request.headers.get("market", "")
    if market_from:
        request.ctx.market_from = market_from
        return

    request_name = request.name.rsplit(".", 1)[-1] if request.name else ""
    # 某些情况要设置过滤的白名单
    if not request_name or request_name in ["static"]:
        request.ctx.market_from = "wechat_service"
    elif not request.path.endswith("call_back/"):
        return general_json_res(403, "where are you from?", 403)


async def check_user(request: Request):
    user_code = request.headers.get("user-code")
    request.ctx.user_id = 0
    if user_code:
        user_id = await UniqCode.decode(user_code)
        if user_id > 0:
            request.ctx.user_id = user_id
